#include "loading_button_p.h"

// Qt's
#include <QHBoxLayout>
#include <QMovie>

LoadingButtonPrivate::LoadingButtonPrivate(LoadingButton* q)
    : QObject{q}
    , m_pLoaddingLabel{nullptr}
    , m_pTextLabel{nullptr}
    , q_ptr{q}
    , m_nTimeout{3000}
    , m_nTimerId{-1}
{
}

LoadingButton::LoadingButton(QWidget* parent)
    : QPushButton(parent)
    , d_ptr{new LoadingButtonPrivate{this}}
{
    Q_D(LoadingButton);

    d->m_pTextLabel = new QLabel(this);

    d->m_pLoaddingLabel = new QLabel(this);
    auto movie = new QMovie{ R"(D:\Desktop\loading.gif)" };
    movie->setScaledSize(QSize(16, 16));
    d->m_pLoaddingLabel->setMovie(movie);

    auto layout = new QHBoxLayout();
    layout->addWidget(d->m_pLoaddingLabel);
    layout->addWidget(d->m_pTextLabel);
    this->setLayout(layout);
}

LoadingButton::LoadingButton(const QString& text, QWidget* parent)
    : QPushButton(parent)
    , d_ptr{ new LoadingButtonPrivate{this} }
{
    Q_D(LoadingButton);

    d->m_pTextLabel = new QLabel(text, this);

    d->m_pLoaddingLabel = new QLabel(this);
    auto movie = new QMovie{ R"(D:\Desktop\loading.gif)" };
    movie->setScaledSize(QSize(16, 16));
    d->m_pLoaddingLabel->setMovie(movie);

    auto layout = new QHBoxLayout();
    layout->addWidget(d->m_pLoaddingLabel);
    layout->addWidget(d->m_pTextLabel);
    this->setLayout(layout);
}

LoadingButton::~LoadingButton()
{}


void LoadingButton::setTimeout(int _timeout)
{
    Q_D(LoadingButton);
    
    d->m_nTimeout = _timeout;
}

int LoadingButton::timeout() const
{
    Q_D(const LoadingButton);

    return d->m_nTimeout;
}

void LoadingButton::setFinished()
{
    Q_D(LoadingButton);

    d->m_pLoaddingLabel->movie()->stop();
    this->killTimer(d->m_nTimerId);
}

void LoadingButton::mouseReleaseEvent(QMouseEvent* me)
{
    Q_D(LoadingButton);

    if (me->button() == Qt::LeftButton) {
        d->m_pLoaddingLabel->movie()->start();
        d->m_nTimerId = this->startTimer(d->m_nTimeout);
    }

    QPushButton::mouseReleaseEvent(me);
}

void LoadingButton::timerEvent(QTimerEvent* te)
{
    Q_D(LoadingButton);

    if (te->timerId() == d->m_nTimerId) {
        d->m_pLoaddingLabel->movie()->stop();
        emit sgnTimeout();
        this->killTimer(d->m_nTimerId);
    }

    QPushButton::timerEvent(te);
}

